﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using MethodWorx.CMS.Content;
using MethodWorx.CMS.Web;
using MethodWorx.CMS.TemplateLanguage;
using MethodWorx.CMS.Configuration;
using MethodWorx.CMS.Administration;
using MethodWorx.CMS.Plugins;
using MethodWorx.CMS.TemplateParser;

namespace MethodWorx.CMS.WebHost
{
    public partial class _PreviewPage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        public Page CmsPage
        {
            get { return this.CmsRequestContext.Page; }
        }

        public CmsRequestContext CmsRequestContext
        {
            get
            {
                return CmsRequestContext.Current;
            }
        }

        public PageTemplate CmsPageTemplate
        {
            get { return this.CmsPage.Template; }
        }

        public string Output
        {
            get 
            {
                PluginService service =
                    new PluginService(
                        WebConfiguration.Instance.Provider.GetUnitOfWorkFactory(),
                        WebConfiguration.Instance.Provider.GetService<IPluginUserDataRepository>(),
                        WebConfiguration.Instance.Provider.GetService<IPluginRepository>());

                var applicationSettings =
                    WebConfiguration.Instance.Provider.GetService<IApplicationSettingsRepository>();

                var plugins = new PluginRepository(
                    WebConfiguration.Instance.Provider,
                    WebConfiguration.Instance.Provider.GetUnitOfWorkFactory(),
                    WebConfiguration.Instance.Provider.GetRepositoryRegistry());

                var parsingEngine = new ParsingEngine(WebConfiguration.Instance.Provider, this.CmsRequestContext.Page.Template,
                                                      new PluginFactory(applicationSettings, plugins), null);


                var t = parsingEngine.GetCompiler().Compile(Web.CmsRequestContext.Current, (ty) => WebConfiguration.Instance.GetService(ty));
                var variables = new Dictionary<string, object>();
                variables.Add("~", this.ResolveUrl("~/"));
                return (string)t.GetType().InvokeMember("Execute",
                                                BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance,
                                                null, t, new object[] { variables });

            }
        }
    }
}
